package com.shj.em.biz.finance.controller;

import com.shj.em.base.controller.BaseController;
import com.shj.em.base.support.ResMsg;
import com.shj.em.biz.finance.dto.OrderReceiptDTO;
import com.shj.em.biz.finance.entity.Receipt;
import com.shj.em.biz.finance.service.ReceiptService;
import com.shj.em.biz.sell.entity.Order;
import com.shj.em.common.annotation.Log;
import com.shj.em.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;


/**
 * <p>
 * 开票信息 前端控制器
 * </p>
 *
 * @author Shen Huang Jian
 * @since 2018-07-14
 */
@RestController
@Slf4j
@RequestMapping("/finance/receipt")
public class ReceiptController extends BaseController<Receipt>{

    @Autowired
    ReceiptService receiptService;

    @GetMapping("/{orderId}")
    public ResMsg<OrderReceiptDTO> findOrderById(@PathVariable("orderId") Long orderId){
        OrderReceiptDTO initDTO = new OrderReceiptDTO();
        Order order = orderService.selectById(orderId);
        initDTO.setOrder(order);

        List<Receipt> list = receiptService.getReceiptsByOrderId(orderId);
        initDTO.setReceiptList(list);

        return ResMsg.ok(initDTO);
    }

    @GetMapping("/findReceiptsByOrderId/{orderId}")
    public ResMsg<List<Receipt>> findPaymentsByOrderId(@PathVariable("orderId") Long orderId){
        List<Receipt> list = receiptService.getReceiptsByOrderId(orderId);
        return ResMsg.ok(list);
    }


    @Log("批量删除发票")
    @DeleteMapping
    public ResMsg batchRemove(@RequestBody Long[] ids){
        receiptService.deleteBatchIds(Arrays.asList(ids));
        return ResMsg.ok();
    }


	@Log("创建开票信息")
	@PostMapping
	public ResMsg add(@RequestBody Receipt receipt){
        try{
            String msg = receiptService.createReceipt(receipt);
            if(StringUtils.isBlank(msg)){
                String canAddReceipt = canAddReceipt(receipt.getOrderId());
                return ResMsg.ok(canAddReceipt);
            }else{
                return ResMsg.error(msg);
            }

        }catch(Exception e){
            log.error("创建开票信息失败", e);
            return ResMsg.error("创建开票信息失败");
        }

	}

    @Log("更新开票信息")
	@PutMapping
	public ResMsg edit(@RequestBody Receipt receipt){
        try{
            String msg = receiptService.updateReceipt(receipt);
            if(StringUtils.isBlank(msg)){
                String canAddReceipt = canAddReceipt(receipt.getOrderId());
                return ResMsg.ok(canAddReceipt);
            }else{
                return ResMsg.error(msg);
            }
        }catch(Exception e){
            log.error("更新开票信息失败", e);
            return ResMsg.error("更新开票信息失败");
        }
	}

    private String canAddReceipt(Long orderId){
        return receiptService.canAddReceipt(orderId) ? "Y" : "N";
    }


}

